package org.example.rpc.framework;


import java.util.HashMap;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * @Desc: 注册中心
 */
public class Registry {
    private final static HashMap<String, Class> map = new HashMap<>();
    private final static ReadWriteLock readWriteLock = new ReentrantReadWriteLock();

    /**
     * 读缓存
     * @param key
     * @return
     */
    public static Class get(String key){
        // 读锁
        Lock writeLock = readWriteLock.writeLock();
        // 写锁
        Lock readLock = readWriteLock.readLock();

        Class v = null;
        readLock.lock();
        try {
            v = map.get(key);
        }finally {
            readLock.unlock();
        }
        if (v != null){
            return v;
        }
        // 缓存中不存在
        writeLock.lock();
        try {
            v = map.get(key);
            if (v==null){
                // 1.查询数据库
                // 2.写入缓存
                map.put(key,v);
            }
        }finally {
            writeLock.unlock();
        }
        return v;
    }

    /**
     * 写缓存
     * @param key
     * @param value
     * @return
     */
    public static Class put(String key, Class value){
        Lock writeLock = readWriteLock.writeLock();
        writeLock.lock();
        try {
            return map.put(key,value);
        }finally {
            writeLock.unlock();
        }
    }

    public static boolean containsKey(String key){
        return map.containsKey(key);
    }

}

